/**
 * 通用删除
 * @url admin/system/base/delete
 * @description 通用删除操作
 */
module.exports = {
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '删除成功' };
		
		// 表名映射配置
		const dbNameMap = {
			user: 'uni-id-users',
			role: 'uni-id-roles',
			permission: 'uni-id-permissions',
			menu: 'opendb-admin-menus'
		};
		
		// 业务逻辑开始-----------------------------------------------------------
		let { type, _id, ids } = data;
		
		if (!type || !dbNameMap[type]) {
			return { code: -1, msg: '类型参数错误' };
		}
		
		if (!_id && !ids) {
			return { code: -1, msg: '请指定要删除的数据' };
		}
		
		let dbName = dbNameMap[type];
		let deleteIds = ids || [_id];
		
		// 根据类型进行特殊检查
		if (type === 'role') {
			// 检查是否有用户使用该角色
			let userRes = await db.collection('uni-id-users')
				.where({ role: _.in(deleteIds) })
				.get();
			if (userRes.data.length > 0) {
				return { code: -1, msg: '该角色正在被使用，无法删除' };
			}
		} else if (type === 'user') {
			// 不能删除自己
			if (deleteIds.includes(uid)) {
				return { code: -1, msg: '不能删除当前登录用户' };
			}
		}
		
		// 删除数据
		await db.collection(dbName)
			.where({ _id: _.in(deleteIds) })
			.remove();
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

